<template>
  <div>
    <el-form>
      <el-button type="warning" @click="addTask">新增</el-button>
    </el-form>
    <el-table
      :data="tableData"
      border
      style="width: 100%">
      <el-table-column
        type="index"
        width="60">
      </el-table-column>
      <el-table-column
        prop="name"
        label="标题"
        width="280">
      </el-table-column>
      <el-table-column
        prop="create_date"
        label="创建日期"
        width="180">
      </el-table-column>
      <el-table-column
        prop="status"
        label="状态"
        width="100">
      </el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button size="mini" @click="editTask(scope.row)">
            编辑
          </el-button>
          <el-button size="mini" type="danger" @click="beginTask(scope.row)">
            开始
          </el-button>
          <el-button size="mini" type="info">
            下载数据
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog :visible.sync="showDialog">
      <v-crawl-editor :form="selectedForm">
        <el-button slot="cancel" @click="showDialog = false">取消</el-button>
      </v-crawl-editor>
    </el-dialog>
  </div>

</template>
<script>
import axios from 'axios'
import timeStamp2String from '@/utils/time'
import CrawlEditor from '@/components/CrawlEditor'
export default {
  created () {
    let that = this
    axios.get('http://127.0.0.1:5000/task')
      .then(function (resp) {
        let d
        for (let i in resp.data) {
          d = resp.data[i]
          let createDate = d.create_date
          if (createDate) {
            d.create_date = timeStamp2String(createDate['$date'])
          }
          console.log(d)
        }
        that.tableData = resp.data
      })
  },
  data () {
    return {
      tableData: [],
      showDialog: false,
      selectedForm: {
        name: '',
        rule: '',
        links: ''
      }
    }
  },
  methods: {
    addTask () {
      console.log(this)
      this.showDialog = true
      this.selectedForm = {
        name: '',
        rule: '',
        links: ''
      }
    },
    editTask (row) {
      console.log(row)
      this.showDialog = true
      let links = ''
      for (let i in row.links) {
        links += row.links[i] + '\n'
      }
      this.selectedForm = {
        name: row.name,
        rule: JSON.stringify(row.rule),
        links: links.slice(0, -1)
      }
    },
    beginTask (row) {
      axios.post('http://127.0.0.1:5000/crawl/' + row['_id']['$oid'])
    }
  },
  components: {
    'v-crawl-editor': CrawlEditor
  }
}
</script>
